package com.dream21th.oauth.service;

import com.dream21th.oauth.remote.AdminFeign;
import com.dream21th.common.ComResp;
import com.dream21th.common.dto.UserDTO;
import com.google.common.collect.Lists;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;
import java.util.List;
import java.util.Objects;


@Component("userDetailsServiceImpl")
public class UserDetailsServiceImpl implements UserDetailsService {


    @Autowired
    private AdminFeign adminFeign;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {

        ComResp<UserDTO> info = adminFeign.info(username);
        UserDTO userDTO=info.getResponseData();
        if(Objects.isNull(userDTO) || Objects.isNull(userDTO.getUserId())){
            return null;
        }
        List<GrantedAuthority> grantedAuthorities = Lists.newArrayList();
        for(String permission: userDTO.getPermissions()){
            GrantedAuthority authority = new SimpleGrantedAuthority(permission);
            grantedAuthorities.add(authority);
        }
        GrantedAuthority authority = new SimpleGrantedAuthority("USER");
        grantedAuthorities.add(authority);
        return new User(userDTO.getUsername(), userDTO.getPassword(), grantedAuthorities);
    }

}
